<script setup>
import CryptoJS from 'crypto-js'
import md5 from 'js-md5'
import qs from 'qs'
import { showToast, showSuccessToast, showFailToast } from 'vant';
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
import axios from 'axios';
import { ref } from 'vue';
import { onMounted, computed } from 'vue';
const isrule = ref(false)
const islogin = ref(false)
const popform = ref({
  telphone: '',
  code: '',
})
// 登录
function userlogin() {
  islogin.value = true
}
onMounted(() => {
  getinit()
})

// 获取短信验证码
const miaonum = ref(59)
const showtext = ref(true)
const timer = ref()

function codeset() {
  showtext.value = false
  if (timer.value) clearInterval(timer.value)
  timer.value = setInterval(() => {
    miaonum.value -= 1
    if (miaonum.value === 0) {
      showtext.value = true
      if (timer.value) clearInterval(timer.value)
      miaonum.value = 59
    }
  }, 1000)
}
const idbol = ref(false)
function getinit() {
  const ua = navigator.userAgent.toLowerCase();//获取判断用的对象
  var isMobile = /Mobile|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua);
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    idbol.value = true
  } else {
    idbol.value = false
  }
}
/**
     * AES 解密
     * @param {*} word 
     * @param {*} keyStr 
     */
function decrypt(word, keyStr) {
  let key = CryptoJS.enc.Utf8.parse(keyStr);
  let decrypt = CryptoJS.AES.decrypt(word, key, {
    vi: key,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  // console.log('aes解密的数据', CryptoJS.enc.Utf8.stringify(decrypt).toString())
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
function getAuthkey(times, midcode, pubkey) {
  // let azparsedata = JSON.parse(window.localStorage.getItem('azinitdata'))
  // console.log(store.getters.initParam)
  // let word = "5c9b10dfff26feff1ae911fbd725a8a6".replace(/\=jia\=/g, "+")
  // console.log('正则处理数据', word)
  // 合成秘钥
  // let codekey = `${times}${pubkey}`
  // let zzkey = md5(codekey.toString().slice(5, 21))
  // console.log('md5data',codekey,codekey.toString().slice(5,21),codekey.toString().slice(5,21).length,zzkey)
  // 解密
  // let jmseckey = decrypt(word, zzkey)
  // localStorage.setItem('aesscekey', jmseckey)
  // console.log('解密数据', jmseckey)
  let mid = midcode
  let jmseckey = '8aa8db54dff7ba4c9cdbc3df7f20c22e'
  console.log('加密数据', times + jmseckey + mid)
  return md5(times + jmseckey + mid);

}
function creatUUID() {
  if (localStorage.getItem('UUID')) {
    return localStorage.getItem("UUID")
  } else {
    // let UUID = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    //   var r = Math.random() * 16 | 0,
    //     v = c == 'x' ? r : (r & 0x3 | 0x8);
    //   return v.toString(16);
    // });
    let keymid = md5(popform.value.telphone)
    localStorage.setItem('UUID', keymid)
    return keymid
  }
}
let userinfomid = ref('')
function activate() {
  userinfomid.value = creatUUID()
  let mid = userinfomid.value
  console.log('初始化激活',mid)
  let times = Date.parse(new Date())
  let subchannel = route.query.subchannel
  let channel = route.query.channel
  let pubkey = '43de0a1deee158e98f5e9aecd8b7e7c0'
  let param = {
    subchannel: subchannel,
    channel: channel,
    pubkey: pubkey,
    authkey: getAuthkey(times, mid, pubkey),
    timestamp: times,
    mid: mid,
    os: 2,
    bundleid: '',
    source: '',
    osver: '',
    net_market: '',
    imei2: '',
    deviceMarket: '',
    nettype: '',
    imei: '',
    sdkver: '',
    devicename: '',
    androidid: '',
    oaid: '',
    mac: "",
    screenpx: "",
    sdkver: '3.0.4'
  }
console.log('param',param)
  axios({
    url: 'https://sdk.nextjoy.com/stat/log/active',
    method: 'post',
    data: qs.stringify(param)
  }).then(res => {
    sendCode(9)
    console.log(res)
  })
}
function sendCode(type) {
  let smstype = type //类型
  let mid = userinfomid.value
  let times = Date.parse(new Date())
  let subchannel = route.query.subchannel
  let channel = route.query.channel
  let pubkey = '43de0a1deee158e98f5e9aecd8b7e7c0'
  let param = {
    subchannel: subchannel,
    channel: channel,
    pubkey: pubkey,
    authkey: getAuthkey(times, mid, pubkey),
    timestamp: times,
    mid: mid,
    mobile: popform.value.telphone,
    smstype: smstype,
    os: 2,
    bundleid: '',
    source: '',
    osver: '',
    net_market: '',
    imei2: '',
    deviceMarket: '',
    nettype: '',
    imei: '',
    sdkver: '',
    devicename: '',
    androidid: '',
    oaid: '',
  }
  console.log('mid', mid, times, channel, subchannel)

  if (popform.value.telphone) {
    axios({
      url: 'https://sdk.nextjoy.com/login/safeauth/sendCodeV2',
      method: 'post',
      data: qs.stringify(param),
    }).then(res => {
      if (res.data.status != '200') {
        showToast(`${res.data.message}`)
      } else {
        codeset()
      }
    }).catch((error) => {
      console.log(error)
    })
  } else {
    let message = '请输入手机号'
    showFailToast(`${message}`)
  }
}
function onsubmit() {
  if (!popform.value.telphone) {
    let message = '请输入手机号'
    showFailToast(`${message}`)
    return false
  } else if (!popform.value.code) {
    let message = '请输入验证码'
    showFailToast(`${message}`)
    return false
  }
  let mid = userinfomid.value
  let times = Date.parse(new Date())
  let subchannel = route.query.subchannel
  let channel = route.query.channel
  let pubkey = '43de0a1deee158e98f5e9aecd8b7e7c0'
  let param = {
    subchannel: subchannel,
    channel: channel,
    pubkey: pubkey,
    authkey: getAuthkey(times, mid, pubkey),
    timestamp: times,
    mid: mid,
    mobile: popform.value.telphone,
    // smstype: smstype,
    code: popform.value.code,
    os: 2,
    bundleid: '',
    source: '',
    osver: '',
    net_market: '',
    imei2: '',
    deviceMarket: '',
    nettype: '',
    imei: '',
    sdkver: '',
    devicename: '',
    androidid: '',
    oaid: ''
  }
  axios({
    url: 'https://sdk.nextjoy.com/login/reglogin/mobileRegLogin',
    method: 'post',
    data: qs.stringify(param),
  }).then(res => {
    if (res.data.status != '200') {
      showToast(`${res.data.message}`)
    } else {
      if (res.data.data.is_reg) {
        console.log('注册')
        islogin.value = false
        issuccess.value = true
        Successtext.value.message = '账号注册成功，点击下方按钮 跳转到App Store下载，进行账号登录。'
      } else {
        console.log('登录')
        islogin.value = false
        issuccess.value = true
        Successtext.value.name = '登录成功'
        Successtext.value.message = '账号登录成功，点击下方按钮 跳转到App Store下载，进行账号登录。'
      }
      // window.open('')
    }
  })
}
const Successtext = ref({
  name: '登录成功',
  message: `账号登录成功，点击下方按钮 跳转到App Store下载，进行账号登录。`,
})
function openhref() {
  try {
    window.open('https://apps.apple.com/cn/app/id1639842761')
  } catch (error) {
    window.location.href = 'https://apps.apple.com/cn/app/id1639842761'
  }
}

const issuccess = ref(false)
const iscode = ref(false)
const iserror = ref(false)
</script>

<template>
  <div class="w-full h-[100vh]">
    <!-- 引导框 -->
    <div class="w-full h-[100vh]  z-[100] fixed left-0 top-0" v-if="idbol">
      <img src="@/assets/anchorpage/mtydpage.jpg" class="w-full h-full object-cover" alt="">
    </div>
    <div class="main w-full h-full relative">
      <div class="w-full h-[3.75rem] bg-[rgba(0,0,0,.6)] flex justify-start items-center">
        <img src="@/assets/anchorpage/icon.png" class="h-[2.5rem] ml-[.9375rem]"/>
      </div>
      <img src="@/assets/anchorpage/logo.png" class="h-[3.375rem] absolute right-[.625rem] top-[4.375rem]"/>
      <img src="@/assets/anchorpage/text.png" class="w-[22.125rem] h-[10.125rem] absolute left-[50%] ml-[-11.0625rem] bottom-[7.5rem]"/>
      <img src="@/assets/anchorpage/btn.png" class="w-[6.375rem] h-[2.625rem] absolute left-[50%] ml-[-3.8125rem] bottom-[5rem]" @click="userlogin()"/>
    </div>

    <!-- 弹框 -->
    <div class="modelbox" v-if="islogin">
      <div class="modexboxcontent">
        <div class=" z-[1045] flex justify-center items-center w-[100vw] h-[96vh]">
          <div>
            <!-- 表单内容 -->
            <div class="modelboxbg w-[19.5625rem] h-[14.9375rem] relative flex justify-center items-start ">
              <div @click="islogin = false" class="absolute w-[1.6875rem] right-1 top-1 mx-2 my-2">
                <img class=" cursor-pointer" src="@/assets/anchorpage/xx.png" alt="">
              </div>
              <div class="mt-[3.125rem]">
                <!-- 表单 -->
                <div class="flex justify-center pt-2">
                  <div class="w-full">
                    <!-- 手机号 -->
                    <div class="px-3 phoneinput w-[15rem] h-[1.975rem] mt-[0.8rem]">
                      <input style="background-color: transparent" type="tel" maxlength="11"
                        class="text-[black] w-full h-full" v-model="popform.telphone" placeholder="请输入手机号">
                    </div>
                    <!-- 验证码 -->
                    <div class="flex mt-[1.6rem]">
                      <div class=" px-3 codeinput w-[11.125rem] h-[1.975rem]">
                        <input style="background-color: transparent" type="tel" class="text-[black] w-full h-full"
                          maxlength="6" v-model="popform.code" placeholder="请输入验证码">
                      </div>
                      <div class="ml-[.25rem]">
                        <button v-if="showtext" @click="activate()"
                          class="bg-[rgb(250,200,36)] w-[4.4375rem] h-[1.875rem] text-[0.7rem] rounded-3xl text-center"
                          :disabled="iscode">发送验证码</button>
                        <button v-if="!showtext" disabled
                          class="bg-[rgb(184,184,184)] w-[4.4375rem] h-[1.875rem] text-[0.7rem] rounded-3xl text-center">剩余{{
                            miaonum
                          }}秒</button>
                      </div>
                    </div>
                    <!-- 立即预约 -->
                    <div class="flex justify-center mt-[2rem]" @click="onsubmit()">
                      <img class="w-[7.1875rem] h-[2.0625rem] cursor-pointer " src="@/assets/anchorpage/bigbutton.png" alt="">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 成功内容 -->
    <div class="modelsuccessbg w-[19.5625rem] h-[14.2933rem] flex justify-center items-end relative" v-if="issuccess">
      <div class="absolute w-[32px] right-1 top-1 mx-2 my-2">
        <img class=" cursor-pointer" src="@/assets/anchorpage/xx.png" alt="" @click="issuccess = false">
      </div>
      <div class="w-full pt-[3.75rem] h-full">
        <p class="w-[90%] mx-auto text-[rgb(156,107,30)] text-center mb-[.9375rem]">{{ Successtext.name }}</p>
        <p class="w-[90%] mx-auto text-[rgb(156,107,30)] text-center"> {{ Successtext.message }}</p>
        <img src="@/assets/anchorpage/bigbutton.png" class="w-[8.125rem] h-[2.4rem] mx-auto mt-[1.25rem]" @click="openhref()"/>
      </div>
      
    </div>
    <!-- 失败内容 -->
    <!-- <div class="modelboxbg  w-[25rem] h-[9.9467rem]" v-if="iserror">
      <div class="flex justify-center pt-2">
        <p class="font-bold">登录失败</p>
      </div>
      <div class="flex justify-center mt-5">
        <p class="text-[black]">信息有误，请填写正确的号码。</p>
      </div>
      <div class="flex justify-center mt-4">
        <div class="errorbutton w-[9.3733rem] h-[2.4rem]  flex justify-center items-center ">
          <p class="text-[rgb(75,37,12)] font-bold">请重新输入</p>
        </div>
      </div>
    </div> -->
  </div>
</template>


<style scoped>
.main{
  background: url(../assets/anchorpage/bg.jpg) no-repeat;
  background-size:cover;
  background-position: center center;
}
/* 弹框代码 */
.modelbox {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 1040;
  background-color: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(15px);

}
.modelboxbg {
  background: url(../assets/anchorpage/bgimg.png) no-repeat;
  background-size: 100% 100%;
}
.phoneinput {
  background: url(../assets/anchorpage/phoneinput.png) no-repeat;
  background-size: 100% 100%;
}

.codeinput {
  background: url(../assets/anchorpage/codeinput.png) no-repeat;
  background-size: 100% 100%;
}

input {
  outline: none;
  font-size: 0.8rem;
}

textarea::placeholder {
  font-size: 0.8rem
}

.errorbutton {
  background: url(../assets/anchorpage/bigbutton.png) no-repeat;
  background-size: 100% 100%;
}

.modelboxbg {
  background: url(../assets/anchorpage/bgimg.png) no-repeat;
  background-size: 100% 100%;
}

.modelsuccessbg {
  background: url(../assets/anchorpage/bgimg.png) no-repeat;
  background-size: 100% 100%;
  position: fixed;
  left: 50%;
  margin-left: -9.8125rem;
  top: 50%;
  margin-top: -7.125rem;
}

</style>
